package cn.itsource._02_rabbitmq_work_queue;

import cn.itsource.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

import static cn.itsource._02_rabbitmq_work_queue.send.WORK_QUEUE_NAME;

//消息接收者
public class rev {
    public static void main(String[] args) throws Exception {
        //获得连接对象
        Connection connection = ConnectionUtil.getConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(WORK_QUEUE_NAME, true, false, false, null);
        /**
         * 消费者接收消息调用此方法
         * @param consumerTag 消费者的标签，在channel.basicConsume()去指定
         * @param envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志
        (收到消息失败后是否需要重新发送)
         * @param properties
         * @param body
         **/
        //设置每个消费者每次只能处理一条数据
        channel.basicQos(1);
        Consumer consume = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                Thread thread = new Thread();
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //消息的内容
                System.out.println(new String(body, "utf-8"));
                System.out.println("id:" + envelope.getDeliveryTag());
                System.out.println("队列名称:" + envelope.getRoutingKey());
                System.out.println("交换机:" + envelope.getExchange());

                //手动签收 long deliveryTag 消息的id, boolean multiple 是否等所有的消息都接收完再签收

                channel.basicAck(envelope.getDeliveryTag(), false);

            }
        };
        //接收消息
        //String basicConsume(String queue, DeliverCallback deliverCallback 接收方式, CancelCallback cancelCallback)
        channel.basicConsume(WORK_QUEUE_NAME, false, consume);
    }
}
